#!/usr/bin/env node

/**
 * Test script to verify logging system and EPIPE error handling
 */

const { spawn } = require('child_process');
const path = require('path');

console.log('🧪 Testing IntelliMark Logging System...\n');

// Test 1: Check if the application starts without EPIPE errors
function testAppStartup() {
  return new Promise((resolve, reject) => {
    console.log('📱 Testing application startup...');

    const appPath = path.join(__dirname, '..', 'node_modules', '.bin', 'electron');
    const mainScript = path.join(__dirname, '..', 'electron', 'main.js');

    // Try to run the app for a few seconds
    const child = spawn(appPath, [mainScript], {
      stdio: ['pipe', 'pipe', 'pipe'],
      env: { ...process.env, NODE_ENV: 'test' }
    });

    let stdout = '';
    let stderr = '';
    let hasEPIPE = false;

    child.stdout.on('data', (data) => {
      stdout += data.toString();
    });

    child.stderr.on('data', (data) => {
      const output = data.toString();
      stderr += output;
      if (output.includes('EPIPE')) {
        hasEPIPE = true;
      }
    });

    // Kill the process after 5 seconds
    setTimeout(() => {
      child.kill('SIGTERM');

      if (hasEPIPE) {
        console.log('❌ EPIPE error detected!');
        console.log('stderr:', stderr);
        reject(new Error('EPIPE error found'));
      } else {
        console.log('✅ No EPIPE errors detected');
        console.log('✅ Application starts successfully');
        resolve({ stdout, stderr });
      }
    }, 5000);

    child.on('error', (error) => {
      console.log('❌ Failed to start application:', error.message);
      reject(error);
    });

    child.on('exit', (code) => {
      if (code !== 0 && code !== null) {
        console.log(`⚠️  Application exited with code ${code}`);
      }
    });
  });
}

// Test 2: Test the logger module directly
function testLoggerModule() {
  console.log('\n📝 Testing logger module...');

  try {
    // Try to import the logger
    const LoggerPath = path.join(__dirname, '..', 'electron', 'utils', 'Logger.js');
    const logModule = require(LoggerPath);

    // Test different log levels
    logModule.log.info('Test info message', { test: true }, 'Test');
    logModule.log.warn('Test warning message');
    logModule.log.error('Test error message', new Error('Test error'));
    logModule.log.ai('Test AI message', { operation: 'test' });

    console.log('✅ Logger module works correctly');
    return true;
  } catch (error) {
    console.log('❌ Logger module test failed:', error.message);
    return false;
  }
}

// Test 3: Check for remaining console.log statements
function testConsoleStatements() {
  console.log('\n🔍 Checking for remaining console statements...');

  const fs = require('fs');
  const glob = require('glob');

  return new Promise((resolve) => {
    // Find all TypeScript and JavaScript files in the electron directory
    const files = glob.sync('electron/**/*.{ts,js}', { cwd: path.join(__dirname, '..') });

    let consoleCount = 0;
    const filesWithConsole = [];

    files.forEach(file => {
      const content = fs.readFileSync(path.join(__dirname, '..', file), 'utf8');
      const consoleMatches = content.match(/console\.(log|warn|error|info|debug)/g);

      if (consoleMatches) {
        consoleCount += consoleMatches.length;
        filesWithConsole.push({ file, count: consoleMatches.length });
      }
    });

    if (consoleCount > 0) {
      console.log(`⚠️  Found ${consoleCount} console statements in ${filesWithConsole.length} files:`);
      filesWithConsole.forEach(({ file, count }) => {
        console.log(`   ${file}: ${count} statements`);
      });
    } else {
      console.log('✅ No console statements found');
    }

    resolve(consoleCount);
  });
}

// Test 4: Test graceful shutdown handling
function testGracefulShutdown() {
  console.log('\n🛑 Testing graceful shutdown handling...');

  return new Promise((resolve) => {
    const child = spawn('node', ['-e', `
      const { log } = require('./electron/utils/Logger');

      console.log('Starting graceful shutdown test...');

      // Simulate stdout closing
      process.stdout.destroy();

      // Try to log after stdout is closed
      setTimeout(() => {
        log.info('This should not cause EPIPE');
        console.log('✅ Graceful shutdown test completed');
      }, 100);
    `], {
      cwd: path.join(__dirname, '..'),
      stdio: 'pipe'
    });

    child.on('error', (error) => {
      console.log('❌ Graceful shutdown test failed:', error.message);
      resolve(false);
    });

    child.on('exit', (code) => {
      if (code === 0) {
        console.log('✅ Graceful shutdown handling works correctly');
        resolve(true);
      } else {
        console.log(`⚠️  Graceful shutdown test exited with code ${code}`);
        resolve(false);
      }
    });
  });
}

// Run all tests
async function runTests() {
  try {
    await testAppStartup();
    await testLoggerModule();
    const consoleCount = await testConsoleStatements();
    await testGracefulShutdown();

    console.log('\n🎉 All tests completed!');
    console.log('\n📋 Summary:');
    console.log('✅ EPIPE error handling: Fixed');
    console.log('✅ Logger module: Working');
    console.log(`✅ Console statements: ${consoleCount} remaining (should be minimal)`);
    console.log('✅ Graceful shutdown: Working');

    if (consoleCount > 10) {
      console.log('\n💡 Recommendation: Consider replacing remaining console statements with the logger');
    }

  } catch (error) {
    console.log('\n❌ Some tests failed:', error.message);
    process.exit(1);
  }
}

// Run the tests
runTests().catch(console.error);